package http

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"go-monitor/common/crypto"
	"go-monitor/common/model"
	"go-monitor/common/utility"
	"go-monitor/server/g"
	"go-monitor/server/service"
)

//获取Agent的公钥
func getAgentPublicKey(Ip string) ([]byte, error) {
	var agentPublicKey []byte
	dbkey := "AgentKey_" + Ip
	isExists, err := service.Redis.Exists(dbkey)
	if isExists {
		getValue, err := service.Redis.GetByte(dbkey)
		if err != nil {
			g.Logger.Error("Get Key fail(GetAgentPublicKey)", err)
		} else {
			b, _ := json.Marshal(getValue)
			if string(b) != "" {
				agentPublicKey = getValue
			} else {
				agentauthdir := g.Root + "/var/auth/agent/" + Ip + ".pem"
				agentPublicKey, err = utility.ReadFileAsBytes(agentauthdir)
				if err != nil {
					g.Logger.Error("read agentpublickey fail:", err)
					return agentPublicKey, err
				} else {
					_, err = service.Redis.Set(dbkey, string(agentPublicKey), 0)
				}
			}
		}

	} else {
		return agentPublicKey, errors.New("Redis has no key" + Ip)
	}
	return agentPublicKey, err
}

//获取Server的公钥
func getServerPublicKey() ([]byte, error) {
	var serverPublicKey []byte
	dbkey := "ServerPublicKey"
	isExists, err := service.Redis.Exists(dbkey)
	if isExists {
		getValue, err := service.Redis.GetByte(dbkey)
		if err != nil {
			g.Logger.Error("Get Key fail(GetServerPublicKey)", err)
		} else {
			b, _ := json.Marshal(getValue)
			if string(b) != "" {
				serverPublicKey = getValue
			} else {
				//定义本地存储key的路径
				authdir := g.Root + "/var/auth/server/"
				serverPublicKey, err := utility.ReadFileAsBytes(authdir + "public.pem")
				if err != nil {
					g.Logger.Error("read serverpublickey fail:", err)
					return serverPublicKey, err
				} else {
					_, err = service.Redis.Set(dbkey, string(serverPublicKey), 0)
				}
			}
		}

	} else {
		//定义本地存储key的路径
		authdir := g.Root + "/var/auth/server/"
		serverPublicKey, err := utility.ReadFileAsBytes(authdir + "public.pem")
		if err != nil {
			g.Logger.Error("read serverpublickey fail:", err)
			return serverPublicKey, err
		} else {
			service.Redis.Set(dbkey, string(serverPublicKey), 0)
		}

	}
	return serverPublicKey, err
}

//时间签名
func CheckCommonSign(req model.CommonSign) bool {
	data, _ := base64.StdEncoding.DecodeString(req.Sign)
	req.Sign = ""
	rbyte, err := json.Marshal(req)
	if err == nil {
		sign, err := crypto.RsaDecrypt(data, model.HTTPSeverPrivateKey)
		if err != nil {
			return false
		}
		if string(sign) != utility.GetMd5String(string(rbyte)) {
			return false
		} else {
			return true
		}
	}
	return false
}
